import { createStore } from 'vuex'
import * as indexApi from '@/api/index.js'

export default createStore({
  state: {
    playlist: { tracks: [{ al: {} }] },
    playCurrentIndex: 0,
    lyric: [],
    currentTime: 0,
    interValId: 0,
    userInfo: {}
  },
  getters: {
    lyricList: function (state) {
      let arr = state.lyric.map((item, index, arr) => {
        let min = item.slice(1, 3);
        let sec = item.slice(4, 6);
        let mill = item.slice(7, 10);

        let preTime = 0;
        if (index > 0) {
          let pre = arr[index - 1];
          preTime = parseInt(pre.slice(1, 3)) * 60 * 1000 + parseInt(pre.slice(4, 6)) * 1000 + parseInt(pre.slice(7, 10));
        }

        return {
          preTime,
          min,
          sec,
          mill,
          lyric: item.slice(11, item.length - 1),
          content: item,
          time: parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill)
        };
      });
      return arr;
    },
  },
  //更新state内部的变量
  mutations: {
    //设置
    setPlaylist: function (state, value) {
      state.playlist = value;
    },

    pushPlayList: function (state, value) {
      state.playlist['tracks'].push(value);
    },

    setPlayIndex: function (state, value) {
      state.playCurrentIndex = value;
    },

    setLyric: function (state, value) {
      state.lyric = value;
    },

    setCurrentTime: function (state, value) {
      state.currentTime = value;
    },
    setuserInfo: function (state, value) {
      value = {
        ...value,
        isLogin: true
      }
      state.userInfo = value;
    },


  },
  actions: {
    async getLyric(content, payload) {
      let result = await indexApi.getLyric(payload);
      content.commit('setLyric', result.lrc.lyric.split(/\n/igs))
    },

    async loginCellphone(content, payload) {
      let data = await indexApi.loginCellphone(payload);
      if (data.code == 200) {
        localStorage.setItem('token', data.token);
        let res = await indexApi.getUserDetail({
          uid: data.account.id
        })
        content.commit('setuserInfo', res);
        localStorage.setItem('userInfo', JSON.stringify(res));
      }

      return data;
    }
  },
  modules: {
  }
})
